engines.all().map((ScriptEngine) => {
    if (engines.myEngine().toString() !== ScriptEngine.toString()) {
        ScriptEngine.forceStop();
    }
});

runtime.loadDex("./zxing-core-3.4.1.dex");
importClass(com.google.zxing.qrcode.QRCodeWriter);
importPackage(com.google.zxing);
importPackage(com.google.zxing.common);
importPackage(com.google.zxing.client.j2se);
importClass(java.util.Hashtable);
importClass(android.graphics.Bitmap);
importClass(java.io.BufferedOutputStream);
importClass(java.io.FileOutputStream);

/* -------------------------------------------------------------------------- */
let qrCode = {
    width: 200,
    height: 200,
    content: "https://www.baidu.com/",
    path: files.join(files.getSdcardPath(), "test.png"),
    margin: 30,
    foregroundColor: "#f700ff",
    backgroundColor: "#6bfaff",
};
createQRCode(qrCode);
app.viewFile(qrCode.path);

function createQRCode(qrCode) {
    let hints = new Hashtable();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    hints.put(EncodeHintType.MARGIN, "" + qrCode.margin);
    let bitMatrix = new QRCodeWriter().encode(qrCode.content, BarcodeFormat.QR_CODE, qrCode.width, qrCode.height, hints);
    let pixels = util.java.array("int", qrCode.width * qrCode.height);
    let foreground_color = android.graphics.Color.parseColor(qrCode.foregroundColor);
    let background_color = android.graphics.Color.parseColor(qrCode.backgroundColor);
    for (let y = 0; y < qrCode.height; y++) {
        for (let x = 0; x < qrCode.width; x++) {
            if (bitMatrix.get(x, y)) {
                pixels[y * qrCode.width + x] = foreground_color;
            } else {
                pixels[y * qrCode.width + x] = background_color;
            }
        }
    }
    let bitmap = Bitmap.createBitmap(qrCode.width, qrCode.height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, qrCode.width, 0, 0, qrCode.width, qrCode.height);
    files.createWithDirs(qrCode.path);
    let bos = new BufferedOutputStream(new FileOutputStream(qrCode.path));
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
    bos.flush();
    bos.close();
    bitmap.recycle();
    return qrCode.path;
}
